package com.xinpu.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinpu.entity.TCompanyUser;
import com.xinpu.service.CompanyUserService;
import com.xinpu.service.ITCompanyUserService;
import com.xinpu.util.PasswordUtils;
import com.xinpu.vo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * CompanyUserController
 *
 * @author ayuan
 * @date 2021/5/24
 */
@RestController
@RequestMapping("companyUser")
public class CompanyUserController {


    @Autowired
    private ITCompanyUserService itCompanyUserService;

    @Autowired
    private CompanyUserService companyUserService;


    /**
     * 管理员列表
     *
     * @return
     */
    @GetMapping("list")
    public ResponseMessage list() {
        return ResponseMessage.ok(companyUserService.getList());
    }

    /**
     * 创建总管理员
     *
     * @param map
     * @return
     */
    @PostMapping("create")
    public ResponseMessage createUser(@RequestBody Map<String, String> map) {
        TCompanyUser admin = itCompanyUserService.getOne(Wrappers.<TCompanyUser>lambdaQuery().eq(TCompanyUser::getAccount, map.get("account")));
        if (admin != null) {
            return ResponseMessage.error("账号不能重复");
        }
        TCompanyUser tAdmin = new TCompanyUser();
        String id = map.get("id");
        if (StringUtils.isNotBlank(id)) {
            tAdmin.setId(Integer.parseInt(id));
        }
        tAdmin.setName(map.get("name"));
        tAdmin.setAccount(map.get("account"));
        String salt = RandomUtil.randomString(6);
        tAdmin.setPassword(PasswordUtils.generatePwd(salt, map.get("password")));
        tAdmin.setSalt(salt);
        tAdmin.setRid(Integer.parseInt(map.get("rid")));
        tAdmin.setPhone(map.get("phone"));
        itCompanyUserService.saveOrUpdate(tAdmin);
        return ResponseMessage.ok();
    }

    /**
     * 删除总管理员
     *
     * @param map
     * @return
     */
    @PostMapping("/delete")
    public ResponseMessage delete(@RequestBody Map<String, String> map) {
        itCompanyUserService.removeById(map.get("id"));
        return ResponseMessage.ok();
    }
}
